package com.yingjia.yingjiauniversity.utils;

import java.io.Serializable;
import java.util.Collection;

/**
 * <this optional similar to guava optional>
 *
 * @author: guoxiangxun
 * @date: 17-5-8 上午10:11
 * @version: v1.0
 */
public final class Optional<T> implements Serializable {
    private static final Optional<?> EMPTY = new Optional();
    private final T arg;
    private final boolean absent;

    private Optional() {
        this.arg = null;
        this.absent = true;
    }

    private Optional(final T arg) {
        if (arg == null) {
            throw new NullPointerException("arg must not be null");
        }
        this.arg = arg;
        this.absent = false;
    }

    public static <T> Optional<T> of(final T arg) {
        return new Optional<T>(arg);
    }

    public static <T> Optional<T> ofNullable(final T nullableReference) {
        return nullableReference == null ? Optional.<T>absent() : new Optional<T>(nullableReference);
    }

    @SuppressWarnings("unchecked")
    public static <T> Optional<T> absent() {
        return (Optional<T>) EMPTY;
    }

    public T get() {
        if (absent) {
            throw new IllegalStateException("Optional.get() cannot be called on an absent value");
        }
        return arg;
    }

    public T or(final T defaultValue) {
        if (absent) {
            return defaultValue;
        }
        return arg;
    }

    public T orNull() {
        if (absent) {
            return null;
        }
        return arg;
    }

    public boolean isPresent() {
        return !absent;
    }

    /**
     * <可处理集合是否为空>
     *
     * @return the boolean
     * @author: guoxiangxun
     * @date: Jun 23, 2017 4:10:11 PM
     * @version: v1.0
     */
    public boolean isEmpty() {
        boolean isEmpty = !isPresent();
        if (!isEmpty && get() instanceof Collection) {
            return ((Collection) get()).size() == 0;
        }
        return isEmpty;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final Optional optional = (Optional) o;

        if (absent != optional.absent) {
            return false;
        }
        return !(arg == null ? optional.arg != null : !arg.equals(optional.arg));
    }

    @Override
    public int hashCode() {
        int result = arg == null ? 0 : arg.hashCode();
        result = 31 * result + (absent ? 1 : 0);
        return result;
    }

    @Override
    public String toString() {
        return absent ? "Optional.absent()" : "Optional.of(" + arg + ")";
    }
}
